<?php

require_once 'model/html5av_audio_video.php';
require_once 'model/html5av_source.php';
require_once 'model/html5av_track.php';

/**
 * Database Abstraction Class for HTML5 AV Manager for Wordpress.
 * Inherit all features of PHP Data Object (PDO).
 */
class html5av_dbal extends PDO {

    private $DB_NAME;
    private $DB_USER;
    private $DB_PASSWD;
    private $DB_HOST;
    private $DB_PREFIX;

    const DBRev = 4;

    public function __construct() {
        global $wpdb;
        $this->DB_NAME = $wpdb->dbname;
        $this->DB_USER = $wpdb->dbuser;
        $this->DB_PASSWD = $wpdb->dbpassword;
        $this->DB_HOST = $wpdb->dbhost;
        $this->DB_PREFIX = $wpdb->base_prefix . 'html5av_';
        $tempHost = explode(':', $this->DB_HOST);
        if (isset($tempHost[1])) {
            $port = $tempHost[1];
        } else {
            $port = 3306;
        }
        unset($tempHost);
        if (!is_numeric($port)) {
            $host = "unix_socket=" . end(explode(':', $this->DB_HOST));
        } else {
            $array = explode(':', $this->DB_HOST);
            $host = "host=" . $array[0];
            if (isset($array[1])) {
                $host .= ";port=" . $array[1];
            }
            unset($array);
        }
        parent::__construct('mysql:' . $host . ';dbname=' . $this->DB_NAME, $this->DB_USER, $this->DB_PASSWD);
    }

    public function getPrefix() {
        return $this->DB_PREFIX;
    }

    public function setUpTables() {
        $this->execFile('main.sql');
        if (get_option('html5av_manager_dbrev') == '0') {
            update_option('html5av_manager_dbrev', self::DBRev);
        }
    }

    public function updateTables() {
        $curRev = (int) get_option('html5av_manager_dbrev');
        if ($curRev == self::DBRev) {
            return;
        }

        if ($curRev < 2) {
            $this->execFile('update/2.sql');
        }
        
        if ($curRev < 4) {
            $this->execFile('update/4.sql');
        }

        update_option('html5av_manager_dbrev', self::DBRev);
    }

    private function execFile($file) {
        global $wpdb;
        $file = html5av_manager::getDir() . "/sql/" . $file;
        $sql = file_get_contents($file);
        $sql = str_replace("_prefix_", $this->DB_PREFIX, $sql);
        $sql = str_replace("_wpprefix_", $wpdb->base_prefix, $sql);
        $this->exec($sql);
        if ($this->errorCode() != 00000) {
            print_r($this->errorInfo());
        }
    }

    public function save($id, $attr, $table, $idname = 'ID') {
        if ($id) {
            $param = array();
            $names = array();
            foreach ($attr as $key => $value) {
                $param[] = $value;
                $names[] = '`' . $key . '`' . "=?";
            }
            $names = implode(', ', $names);
            $sql = "UPDATE `" . $this->getPrefix() . $table . "` 
            SET $names 
            WHERE `$idname`=?;";
            $prepare = $this->prepare($sql);
            $param[] = $id;
            $prepare->execute($param);
        } else {
            $param = array();
            $names = array();
            $values = array();
            foreach ($attr as $key => $value) {
                $param[':param_' . $key] = $value;
                $names[] = '`' . $key . '`';
                $values[] = ':param_' . $key;
            }
            $names = implode(', ', $names);
            $values = implode(', ', $values);
            $sql = "INSERT INTO `" . $this->getPrefix() . $table . "` ($names) 
            VALUES ($values);";
            $prepare = $this->prepare($sql);
            $prepare->execute($param);
            $id = $this->lastInsertId();
        }
        if ($prepare->errorCode() != 00000) {
            print_r($prepare->errorInfo());
        }
        return $id;
    }

    public function delete($id, $table, $idname = 'ID') {
        if ($id) {
            $sql = "DELETE FROM `" . $this->getPrefix() . $table . "` WHERE `$idname`=?;";
            $prepare = $this->prepare($sql);
            $prepare->execute(array($id));
            if ($prepare->errorCode() != 00000) {
                print_r($prepare->errorInfo());
            }
            return false;
        }
        return $id;
    }

    static public function toArray($objects, $name) {
        $objects = (array) $objects;
        $startPosition = strlen($name) + 1;
        array_shift($objects);
        $array = array();
        foreach ($objects as $property => $value) {
            $array[(string) trim(substr($property, $startPosition))] = $value;
        }
        return $array;
    }

}